package com.common.servlet;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;
import com.common.utils.SystemConstants;

public class AttributeListener implements HttpSessionListener {

	private static Logger log = Logger.getLogger(AttributeListener.class.getName());

	// 保存当前登录的所有用户
	private static Map loginUser = Collections.synchronizedMap(new HashMap());

	// 用这个作为session中的key
	public static String SESSION_LOGIN_NAME = SystemConstants.SESSIONNAME;

	/**
	 * 获取当前登录在线用户列表
	 * @return
	 */
	public static Map getOnlineSession(){
		return loginUser;
	}

	/**
	 * 删除重复登录session
	 */
	public static void remove(String userid){
		loginUser.remove(userid);
	}

	public void sessionCreated(HttpSessionEvent arg0) {
		log.debug("++++++AttributeListener sessionCreated 开始++++++");

	}

	public void sessionDestroyed(HttpSessionEvent arg0) {
		log.debug("++++++AttributeListener sessionDestroyed 开始++++++");
		HttpSession session = arg0.getSession();
		if (session != null) {
			// 删除单一登录中记录的变量
			if(session.getAttribute(SESSION_LOGIN_NAME)!=null){
				String userid =  (String)session.getAttribute(SESSION_LOGIN_NAME);
				loginUser.remove(userid);
			}
		}
		log.debug("++++++AttributeListener sessionDestroyed 结束++++++");

	}

}
